package com.ohuang.crashhandler;



import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.ohuang.crashhandler.share.Share2;
import com.ohuang.crashhandler.share.ShareContentType;
import com.ohuang.crashhandler.share.ShareFileUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class CrashListActivity extends Activity {
    Button button, button1;
    ListView recyclerView;
    MyAdapter adapter;

    TextView tv_title;
    List<String> data = new ArrayList<>();
    boolean isRun = false;

    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_crash_list);
        button = findViewById(R.id.btn_1);
        button1 = findViewById(R.id.btn_2);
        recyclerView = findViewById(R.id.recycler_View);
        tv_title=findViewById(R.id.tv_title);
        adapter = new MyAdapter(this, data);
        recyclerView.setAdapter(adapter);
        String appName = getAppName(this);
        if (appName!=null) {
            tv_title.setText(appName);
        }
        adapter.setTextOnClick(new MyAdapter.TextOnClick() {
            @Override
            public void onClick(int p, String s) {
                Intent intent = new Intent(CrashListActivity.this, CrashLogActivity.class);
                intent.putExtra("filename", s);
                startActivity(intent);
            }

            @Override
            public void onLongClick(View view, int p, String s) {
                PopupMenu popup = new PopupMenu(CrashListActivity.this,view);
                popup.getMenuInflater().inflate(R.menu.menu_crash_list_output, popup.getMenu());
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        int itemId = item.getItemId();
                        if (itemId == R.id.deleteFile) {
                            FileUtilsDelete.delete(getFilesDir().getAbsolutePath() + "/crashLog/"+s);
                            new Thread(runnable).start();
                        } else if (itemId == R.id.outputFile) {
                            String path=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
                            String pageName=AppUtil.getPackageName(CrashListActivity.this);
                            path=path+"/"+pageName+"/crashLog/";
                             try {

                                 FileUtilsDelete.copyFile(new File(getFilesDir().getAbsolutePath() + "/crashLog/"+s)
                                         ,new File(path+s));
                                 Toast.makeText(CrashListActivity.this, "已导出 path="+path, Toast.LENGTH_LONG).show();
                             }catch (Exception e){
                                 Toast.makeText(CrashListActivity.this, "导出失败 "+e.toString(), Toast.LENGTH_LONG).show();
                             }
                        }else if (itemId == R.id.sharedFile){
                            String path=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
                            String pageName=AppUtil.getPackageName(CrashListActivity.this);
                            path=path+"/"+pageName+"/crashLog/";
                            String outFileName=path+s;
                            try {

                                FileUtilsDelete.copyFile(new File(getFilesDir().getAbsolutePath() + "/crashLog/"+s)
                                        ,new File(outFileName));
                                Uri uri = ShareFileUtil.getFileUri(CrashListActivity.this, ShareContentType.FILE, new File(outFileName));
                                new Share2.Builder(CrashListActivity.this).setContentType(ShareContentType.FILE).setShareFileUri(uri)
                                        .build().shareBySystem();
                            }catch (Exception e){
                                Toast.makeText(CrashListActivity.this, "分享失败 "+e.toString(), Toast.LENGTH_LONG).show();
                            }
                        }
                        return true;
                    }
                });
                popup.show();
            }


        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(runnable).start();
            }
        });

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isRun) {
                    data.clear();
                    adapter.notifyDataSetChanged();
                    new Thread(runnableDelete).start();
                }
            }
        });
        new Thread(runnable).start();
        String pageName = AppUtil.getAppName(this);
        setTitle(pageName + "_Exception");

    }

    public static String getAppName(Context context) {

        try {

            PackageManager packageManager = context.getPackageManager();

            PackageInfo packageInfo = packageManager.getPackageInfo(

                    context.getPackageName(), 0);

            int labelRes = packageInfo.applicationInfo.labelRes;

            return context.getResources().getString(labelRes);

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected( MenuItem item) {
        return super.onContextItemSelected(item);
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (!isRun) {
                isRun = true;
                data.clear();
                readAllFile();
                isRun = false;
            }

        }
    };

    private Runnable runnableDelete = new Runnable() {
        @Override
        public void run() {
            if (!isRun) {
                isRun = true;
                FileUtilsDelete.delete(getFilesDir().getAbsolutePath() + "/crashLog/");
                isRun = false;
            }

        }
    };


    private void readAllFile() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String path = getFilesDir().getAbsolutePath() + "/crashLog/";
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File fa[] = dir.listFiles();
            for (int i = 0; i < fa.length; i++) {
                if (fa[i].isDirectory()) {

                } else {
                    data.add(fa[i].getName());
                }
            }
            recyclerView.post(runnableUi);
        }
    }

    private Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            adapter.notifyDataSetChanged();
        }
    };
}